import http from './HTTP';
import ObjUtils from '../obj_utils';


let GameConfig = {

    serverConfig: null,

    loadConfig(cfgname){
        if (this.serverConfig) {
            return;
        }
        let self = this;
        http.Get('remotecfg', {cfgfile: cfgname}, ret => {
            console.log('服务器配置 ==== ', ret);
            if (!ret.errcode) {
                GameConfig.serverConfig = ret;
                self.__checkDefaultConfig(ret);

                if(ShSdk.configCallback && ShSdk.Types.isFunction(ShSdk.configCallback)){
                    ShSdk.configCallback(ret);
                }
            }
        });
    },

    /**
     * @return {boolean}
     */
    isGMUser() {

        let userId = ShSdk.GameData.getUserId().toString();

        /* eslint-disable */
        let cfg = this.getServerCfg();
        if (cfg && cfg.testuser) {
            let len = cfg.testuser.length;
            for (let i = 0; i < len; ++i) {
                if (cfg.testuser[i].toString() === userId) {  // 隐式转换....
                    return true;
                }
            }
        }

        // 测试Id
        if(ShSdk.$TestId$ && ShSdk.$TestId$ === userId){
            return true;
        }

        return false;
    },


    //获取服务器配置
    getServerCfg() {
        let localServerConfig = ShSdk.config.serverConfig;

        // if (ShSdk.isWebTest()) {
        //     return localServerConfig;
        // }

        if(ShSdk.UseLocalServerConfig){
            return localServerConfig;
        }

        if (GameConfig.serverConfig) {
            if (GameConfig.serverConfig.ignoreVersion === ShSdk.config.version) {
                return localServerConfig;
            }
            return GameConfig.serverConfig;
        }
        return localServerConfig;
    },

    __checkDefaultConfig(cfg) {
        let serverConfig = ShSdk.config.serverConfig;
        for (let k in serverConfig) {
            if (!cfg.hasOwnProperty(k)) {  // eslint-disable-line
                if (window.ShSdk.isWebTest()) {
                    console.warn('服务器配置可能错误......k:', k);
                }
                cfg[k] = ObjUtils.deepClone(serverConfig[k]);
            }
        }
    },
};


export default GameConfig;
